# -*- coding: UTF-8 -*-

import os
import numpy as np

# too lazy... no comments here


def getChannel(image, index):
    channel = image[:, :, index]
    return channel


def getChannelMean(image, index):
    mean = np.mean(image[:, :, index])
    return mean


def getGivenChannelMean(image, channels):
    channel_max = image.shape[2] - 1
    sample = []
    for channel in channels:
        correct_channel = max(min(channel_max, channel), 0)
        sample.append(getChannelMean(image, correct_channel))
    return tuple(sample)


def checkEmptyData(data):
    is_data_empty = (len(data) <= 0)
    if is_data_empty:
        return False
    return True


def checkEmptyFile(file_path):
    is_file_exist = os.path.isfile(file_path)
    if not is_file_exist:
        error_str = "No Such File " + file_path
        raise Exception(error_str)


def createEmptyDir(dir_path):
    is_dir_exist = os.path.isdir(dir_path)
    if not is_dir_exist:
        os.makedirs(dir_path)


def checkEmptyDir(dir_path):
    is_dir_exist = os.path.isdir(dir_path)
    if not is_dir_exist:
        error_str = "No Such Dir " + dir_path
        raise Exception(error_str)


def checkListLength(parameter, length):
    if len(parameter) < length:
        error_str = "Parameter Error: " + str(parameter) + ", but " + \
            str(length) + " elements at least."
        raise Exception(error_str)


def checkMethod(method, method_tuple):
    correct_method = (method in method_tuple)
    if not correct_method:
        print("Available Method: ", method_tuple)
        error_str = "No Such Method: " + method
        raise Exception(error_str)


def flexibleOTSU(gray_histogram):
    answer = [0, 100]
    sum_pixel = gray_histogram.__len__()
    if sum_pixel <= 1:
        return answer
    for threshold in range(10, 250):
        w1_all = 0
        w0_all = 0
        u1_all = []
        u0_all = []
        for gray in gray_histogram:
            if gray < threshold:
                w1_all += 1
                u1_all.append(gray)
            else:
                w0_all += 1
                u0_all.append(gray)
        if (w1_all == 0) or (w0_all == 0):
            continue
        u1 = np.mean(u1_all)
        u0 = np.mean(u0_all)
        w1 = (w1_all + 0.0) / sum_pixel
        w0 = (w0_all + 0.0) / sum_pixel
        g = w0 * w1 * (u0 - u1)**2
        if g > answer[0]:
            answer[0] = g
            answer[1] = threshold
    return answer
